package com.yqd.lesson.futures

import akka.actor._
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
import scala.concurrent.duration._
import scala.util.Success
import scala.util.Failure

case object AskNameMessage

class FutureActor extends Actor {
  def receive = {
    case AskNameMessage => // respond to the 'ask' request
      Thread.sleep(1000 * 3)
      sender ! "Fred"
    case _ => println("that was unexpected")
  }
}
object FutureActor extends App{
  //create the system and actor
  val system = ActorSystem("AskDemoSystem")
  val myActor = system.actorOf(Props[FutureActor], name="myActor")

  //阻塞
  implicit val timeout = Timeout(5 seconds)
  val future = myActor ? AskNameMessage
  val result = Await.result(future, timeout.duration).asInstanceOf[String]
  println("block:" + result)

  //由于mapto返回的是future可以用非阻塞的方法
  val future2: Future[String] = ask(myActor, AskNameMessage).mapTo[String]
  import system._
  val result2 = future2.onComplete({
    case Success(msg) => {
      println("nonblock:" + msg)
    }
    case Failure(e) => {
      e.printStackTrace()
    }
  })
  println("nonblock msg!")

  system.terminate()
}
